﻿package scripts{
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.net.URLRequest;
	import flash.system.Security;
	
	public class loadYouTubeVideo extends MovieClip {
		private var _myPlayer:Object;
		private var _played:Boolean;
		private var _loadVideoFrozer:Boolean;
		private var _playBtn:Sprite;
		private var _myLoader:Loader;
		
		private var _width:Number;
		private var _height:Number;
		private var _videoID:String;
		public function loadYouTubeVideo(videoID:String, width:Number=500, height:Number=500) {
			// constructor code
			super();
			_width=width;
			_height=height;
			this.videoID=videoID;
			addEventListener(Event.ADDED_TO_STAGE,initLoader);
		}

		public function get videoID():String
		{
			return _videoID;
		}

		public function set videoID(value:String):void
		{
			_videoID = value;
		}

		private function initLoader(e:Event):void{
			_played=false;
			_loadVideoFrozer=false;
			_myLoader=new Loader();
			_myLoader.load(new URLRequest("http://www.youtube.com/apiplayer?version=3"));
			//_myLoader.load(new URLRequest("http://www.youtube.com/v/"+videoID+"?version=3"));
			_myLoader.contentLoaderInfo.addEventListener(Event.INIT, onLoaderInit);
			removeEventListener(Event.ADDED_TO_STAGE,initLoader);
		}
		private function onLoaderInit(e:Event):void{
			this.addChild(_myLoader);
			_myPlayer=_myLoader.content;
			_myPlayer.addEventListener("onReady",onPlayerReady);
			_myLoader.contentLoaderInfo.removeEventListener(Event.INIT, onLoaderInit);
		}
		private function onPlayerReady(e:Event):void{
			_myPlayer.setSize(_width,_height);
			_loadVideoFrozer=true;
			stage.addEventListener("PLAY_VIDEO",playOrPause,true);
		}
		public function playOrPause(e:Event):void{
			if(e.target.parent.videoID == this.videoID){			
				if(_loadVideoFrozer){
					this._myPlayer.cueVideoById(this.videoID,0);
					_loadVideoFrozer=false;
				}
				if(!_played){
					_myPlayer.playVideo();
					_played=true;
				}
				else{
					_myPlayer.pauseVideo();
					_played=false;
				}
			}
		}
	}
}

